/**
 * Created by IntelliJ IDEA.
 * User: LuckSuper
 * Date: 12-1-14
 * Time: 上午9:25
 * To change this template use File | Settings | File Templates.
 */

import com.bmc.arsys.api.*;

import java.util.*;

public class BMCTest {
    private ARServerUser server;
    private String formName = "HelloJavaApi";

    public static void main(String[] args) {
        System.out.println("Hello World!!");
        BMCTest bmcTest = new BMCTest();
        System.out.println(Constants.AR_CORE_STATUS);
        System.out.println(Constants.AR_CORE_STATUS);
        bmcTest.connect();
        String id = bmcTest.createEntry("William", "This is the Java API Test", "This is a char test!!");
        bmcTest.queryEntriesByQual("1=1 and 1=1");
        System.out.println(id);
        bmcTest.cleanup();
    }

    public BMCTest() {
        server = new ARServerUser();
        server.setServer("vm-lust");
        server.setUser("Administrator");
        server.setPassword("Pass01!");
    }

    void connect() {
        try {
            server.verifyUser();
            System.out.println("Success!!");
        } catch (ARException e) {
            System.out.println(server.getUser());
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public String createEntry(String submitter, String description, String test) {
        String entryOutId = "";
        Entry entry = new Entry();
        entry.put(2, new Value(submitter));
        entry.put(8, new Value(description));
        int cChr_CharId = 536870914;
        entry.put(cChr_CharId, new Value(test));
        try {
            entryOutId = server.createEntry(formName, entry);
        } catch (ARException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return entryOutId;
    }

    void modifyEntry(String entryId) {
        try {
            Entry entry = server.getEntry(formName, entryId, null);
            entry.put(Constants.AR_CORE_SHORT_DESCRIPTION,
                    new Value("Modified by JavaApiTest"));
            server.setEntry(formName, entryId, entry, null, 0);
            System.out.println();
            System.out.println("Entry #" + entryId +
                    "Modified successfully.");
        } catch (ARException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    void queryEntryByID(String entryId) {
        System.out.println();
        System.out.println("Retrieving entry with entry ID#" + entryId);
        try {
            Entry entry = server.getEntry(formName, entryId, null);
            if (entry == null) {
                System.out.println("No date found for ID#" + entryId);
                return;
            } else {
                Set<Integer> fields = entry.keySet();
                for (Integer fieldId : fields) {
                    Field field = server.getField(formName, fieldId.intValue());
                    Value value = entry.get(fieldId);
                    System.out.print(field.getName().toString());
                    System.out.print(":" + value);
                    System.out.print(",ID:" + field.getFieldID());
                    System.out.print("Field Type:" + field.getDataType());
                    if (field instanceof DateTimeField) {
                        System.out.print(",DateTime value:");
                        Timestamp callDateTimeTS = (Timestamp) value.getValue();
                        if (callDateTimeTS != null) {
                            System.out.print(callDateTimeTS.toDate());
                        }
                    }
                    System.out.print("");
                }
            }
        } catch (ARException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    void queryEntriesByQual(String qualStr) {
        System.out.println();
        System.out.println("Retrieving entries with qualification " + qualStr);
        try {
            List<Field> fields = server.getListFieldObjects(formName);
            QualifierInfo qual = server.parseQualification(qualStr, fields, null,
                    Constants.AR_QUALCONTEXT_DEFAULT);
            int[] filedIds = {2, 7, 8};
            OutputInteger nMatches = new OutputInteger();
            List<SortInfo> sortOrder = new ArrayList<SortInfo>();
            sortOrder.add(new SortInfo(2, Constants.AR_SORT_DESCENDING));
            List<Entry> entryList = server.getListEntryObjects(formName, qual,
                    0, Constants.AR_NO_MAX_LIST_RETRIEVE, sortOrder, filedIds, true, nMatches);
            System.out.println("Query returned " + nMatches + " matches.");
            if (nMatches.intValue() > 0) {
                System.out.println("Request Id    " + "Short Description");
                for (int i = 0; i < entryList.size(); i++) {
                    System.out.println(entryList.get(i).getEntryId() + "   " +
                            entryList.get(i).get(Constants.AR_CORE_SHORT_DESCRIPTION)
                    );
                }
            }
        } catch (ARException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }


    public void ARExceptionHandler(ARException e, String errorMessage) {
        System.out.println(errorMessage);
        printStatusList(server.getLastStatus());
        System.out.println("Stack Trace:");
        e.printStackTrace();
    }

    public void printStatusList(List<StatusInfo> statusInfoList) {
        if (statusInfoList == null || statusInfoList.size() == 0) {
            System.out.println("Status List is empty");
            return;
        }
        System.out.print("Message type: ");
        switch (statusInfoList.get(0).getMessageType()) {
            case Constants.AR_RETURN_OK:
                System.out.println("Note");
                break;
            case Constants.AR_RETURN_WARNING:
                System.out.println("Warning");
                break;
            case Constants.AR_RETURN_ERROR:
                System.out.println("Error");
                break;
            case Constants.AR_RETURN_FATAL:
                System.out.println("Fatal Error");
            default:
                System.out.println("Unknown (" +
                        statusInfoList.get(0).getMessageType() + " )");
                break;
        }
        System.out.println("Status List:");
        for (int i = 0; i < statusInfoList.size(); i++) {
            System.out.println(statusInfoList.get(i).getMessageText());
            System.out.println(statusInfoList.get(i).getAppendedText());
        }
    }

    public void cleanup() {
        server.logout();
        System.out.println();
        System.out.println("User Logged Out.");
    }

}
